const express = require('express');
const router = express.Router();
const db = require('../config/database');

// 获取模板分类列表
router.get('/', async (req, res) => {
  try {
    const { populate } = req.query;
    
    let query = `
      SELECT 
        tt.id,
        tt.name,
        tt.description,
        tt.sort_order,
        tt.created_at,
        tt.updated_at
    `;
    
    if (populate === '*') {
      query += `,
        COUNT(t.id) as template_count
      FROM template_types tt
      LEFT JOIN templates t ON tt.id = t.type_id AND t.is_public = TRUE
      GROUP BY tt.id
      ORDER BY tt.sort_order ASC, tt.created_at DESC
      `;
    } else {
      query += `
      FROM template_types tt
      ORDER BY tt.sort_order ASC, tt.created_at DESC
      `;
    }
    
    const [rows] = await db.execute(query);
    
    const data = rows.map(row => ({
      id: row.id,
      attributes: {
        name: row.name,
        description: row.description,
        sort_order: row.sort_order,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && {
          template_count: row.template_count || 0
        })
      }
    }));
    
    res.json({ data });
  } catch (error) {
    console.error('获取模板分类失败:', error);
    res.status(500).json({ error: '获取模板分类失败' });
  }
});

module.exports = router;